package com.qf.myshop.dao.impl;

import com.qf.myshop.dao.ProductDAO;
import com.qf.myshop.entity.Product;
import com.qf.myshop.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDAOImpl implements ProductDAO {
    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public long count(int ntid) throws SQLException {
        return queryRunner.query(JDBCUtils.getConnection(),
                "select count(1) from product where t_id = ?",
                new ScalarHandler<>(), ntid);
    }

    @Override
    public List<Product> findAll(int ntid, int skip, int pageSize) throws SQLException {
        return queryRunner.query(JDBCUtils.getConnection(), "select * from product where t_id = ? limit ?, ?",
                new ResultSetHandler<List<Product>>() {
                    @Override
                    public List<Product> handle(ResultSet rs) throws SQLException {
                        List<Product> list = new ArrayList<>();
                        while (rs.next()){
                            list.add(new Product(
                                    rs.getInt("p_id"),
                                    rs.getInt("t_id"),
                                    rs.getString("p_name"),
                                    rs.getTimestamp("p_time"),
                                    rs.getString("p_image"),
                                    rs.getDouble("p_price"),
                                    rs.getInt("p_state"),
                                    rs.getString("p_info")
                            ));
                        }
                        return list;
                    }
                }, ntid, skip, pageSize);
    }

    @Override
    public Product findById(int npid) throws SQLException {
        return queryRunner.query(JDBCUtils.getConnection(), "select * from product where p_id = ?",
                new ResultSetHandler<Product>() {
                    @Override
                    public Product handle(ResultSet rs) throws SQLException {
                        while (rs.next()){
                            return new Product(
                                    rs.getInt("p_id"),
                                    rs.getInt("t_id"),
                                    rs.getString("p_name"),
                                    rs.getTimestamp("p_time"),
                                    rs.getString("p_image"),
                                    rs.getDouble("p_price"),
                                    rs.getInt("p_state"),
                                    rs.getString("p_info")
                            );
                        }
                        return null;
                    }
                }, npid);
    }
}
